/*
 * Copyright 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package catchup.app.data

import coil.intercept.Interceptor
import coil.request.ImageResult
import coil.size.pxOrElse
import okhttp3.HttpUrl.Companion.toHttpUrl

/** A Coil [Interceptor] which appends query params to Unsplash urls to request sized images. */
// TODO move this to just the unsplash subproject when coil's imageloader is exposed
object UnsplashSizingInterceptor : Interceptor {
  override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
    val data = chain.request.data
    val widthPx = chain.size.width.pxOrElse { -1 }
    val heightPx = chain.size.height.pxOrElse { -1 }
    if (
      widthPx > 0 &&
        heightPx > 0 &&
        data is String &&
        data.startsWith("https://images.unsplash.com/photo-")
    ) {
      val url =
        data
          .toHttpUrl()
          .newBuilder()
          .addQueryParameter("w", widthPx.toString())
          .addQueryParameter("h", heightPx.toString())
          .build()
      val request = chain.request.newBuilder().data(url).build()
      return chain.proceed(request)
    }
    return chain.proceed(chain.request)
  }
}
